<?php

/******************************************************************************
 *
 *	PROJECT: Flynax Classifieds Software
 *	VERSION: 4.0.1
 *	LISENSE: FL87MPRYOA0R - http://www.flynax.com/license-agreement.html
 *	PRODUCT: Auto Classifieds
 *	DOMAIN: www.siyaradiali.com
 *	FILE: ACCOUNT_FIELDS.INC.PHP
 *
 *	This script is a commercial software and any kind of using it must be 
 *	coordinate with Flynax Owners Team and be agree to Flynax License Agreement
 *
 *	This block may not be removed from this file or any other files with out 
 *	permission of Flynax respective owners.
 *
 *	Copyrights Flynax Classifieds Software | 2012
 *	http://www.flynax.com/
 *
 ******************************************************************************/

/* ext js action */
if ($_GET['q'] == 'ext')
{
	/* system config */
	require_once( '../../includes/config.inc.php' );
	require_once( RL_ADMIN_CONTROL . 'ext_header.inc.php' );
	require_once( RL_LIBS . 'system.lib.php' );
	
	/* date update */
	if ($_GET['action'] == 'update' )
	{
		$reefless -> loadClass( 'Actions' );
		
		$type = $rlValid -> xSql( $_GET['type'] );
		$field = $rlValid -> xSql( $_GET['field'] );
		$value = $rlValid -> xSql( nl2br($_GET['value']) );
		$id = $rlValid -> xSql( $_GET['id'] );
		$key = $rlValid -> xSql( $_GET['key'] );

		$updateData = array(
			'fields' => array(
				$field => $value
			),
			'where' => array(
				'ID' => $id
			)
		);
		
		$rlHook -> load('apExtAccountFieldsUpdate');
		
		$rlActions -> updateOne( $updateData, 'account_fields');
		exit;
	}
	
	/* data read */
	$limit = $rlValid -> xSql( $_GET['limit'] );
	$start = $rlValid -> xSql( $_GET['start'] );
	$sort = $rlValid -> xSql( $_GET['sort'] );
	$sortDir = $rlValid -> xSql( $_GET['dir'] );
	
	$langCode = $rlValid -> xSql( $_GET['lang_code'] );
	$phrase = $rlValid -> xSql( $_GET['phrase'] );
	
	$sql = "SELECT SQL_CALC_FOUND_ROWS DISTINCT `T1`.*, `T2`.`Value` AS `name` ";
	$sql .= "FROM `". RL_DBPREFIX ."account_fields` AS `T1` ";
	$sql .= "LEFT JOIN `".RL_DBPREFIX."lang_keys` AS `T2` ON CONCAT('account_fields+name+',`T1`.`Key`) = `T2`.`Key` AND `T2`.`Code` = '". RL_LANG_CODE ."' ";
	$sql .= "WHERE `T1`.`Status` <> 'trash' ";
	
	if ( $_GET['action'] == 'search' )
	{
		$search_fields = array('Name', 'Type', 'Required', 'Map', 'Status');
		
		foreach ($search_fields as $item)
		{
			if ( $_GET[$item] != '' )
			{
				$s_value = $rlValid -> xSql($_GET[$item]);
				$sql .= $item == 'Name' ? "AND `T2`.`Value` LIKE '%{$s_value}%' " : "AND `T1`.`{$item}` = '{$s_value}' ";
			}
		}
	}
	
	if ( $sort )
	{
		$sortField = $sort == 'name' ? "`T2`.`Value`" : "`T1`.`{$sort}`";
		$sql .= "ORDER BY {$sortField} {$sortDir} ";
	}
	$sql .= "LIMIT {$start}, {$limit}";
	
	$rlHook -> load('apExtAccountFieldsSql');
	
	$data = $rlDb -> getAll($sql);

	foreach ( $data as $key => $value )
	{
		$data[$key]['Type'] = $l_types[$data[$key]['Type']];
		$data[$key]['Required'] = $data[$key]['Required'] ? $lang['yes'] : $lang['no'] ;
		$data[$key]['Map'] = $data[$key]['Map'] ? $lang['yes'] : $lang['no'] ;
		$data[$key]['Status'] = $GLOBALS['lang'][$data[$key]['Status']];
		
		$rlHook -> load('apExtAccountFieldsData');
	}

	$count = $rlDb -> getRow( "SELECT FOUND_ROWS() AS `count`" );
	
	$reefless -> loadClass('Json');
	
	$output['total'] = $count['count'];
	$output['data'] = $data;

	echo $rlJson -> encode( $output );
}
/* ext js action end */

else
{
	$rlHook -> load('apPhpAccountFieldsTop');
	
	/* additional bread crumb step */
	if ($_GET['action'])
	{
		$bcAStep = $_GET['action'] == 'add' ? $lang['add_field'] : $lang['edit_field'] ;
	}
	
	/* get all data formats */
	$data_formats = $rlDb -> fetch( '*', array( 'Parent_ID' => '0', 'Status' => 'active' ), "AND `Key` <> 'currency' ORDER BY `Position`", null, 'data_formats' );
	$data_formats = $rlLang -> replaceLangKeys( $data_formats, 'data_formats', 'name', RL_LANG_CODE, 'admin' );

	$rlSmarty -> assign_by_ref( 'data_formats', $data_formats );
	
	/* load fields class */
	$reefless -> loadClass( 'Fields', 'admin' );
	
	if ($_GET['action'] == 'add' || $_GET['action'] == 'edit')
	{
		/* get account types */
		$account_types = $rlDb -> fetch( array('ID', 'Key'), null, "WHERE `Status` = 'active' ORDER BY `Position`", null, 'account_types' );
		$account_types = $rlLang -> replaceLangKeys( $account_types, 'account_types', 'name', RL_LANG_CODE, 'admin' );

		$rlSmarty -> assign_by_ref( 'account_types', $account_types );
		
		if ($_GET['action'] == 'edit')
		{
			$e_key = $rlValid -> xSql($_GET['field']);

			// get current field information
			$field_info = $rlDb -> fetch( '*', array( 'Key' => $e_key ), "AND `Status` <> 'trash'", null, 'account_fields', 'row' );
			
			if ( empty($field_info) )
			{
				$errors[] = $lang['notice_field_not_found'];
			}
			else 
			{
				if ( !$_POST['fromPost'] )
				{
					// common fields
					$_POST['key'] = $e_key;
					$_POST['required'] = $field_info['Required'];
					$_POST['map'] = $field_info['Map'];
					$_POST['status'] = $field_info['Status'];
					$_POST['type'] = $field_info['Type'];
					
					// get names
					$e_names = $rlDb -> fetch( array( 'Code', 'Value' ), array( 'Key' => 'account_fields+name+'.$e_key ), "AND `Status` <> 'trash'", null, 'lang_keys' );
					foreach ($e_names as $nKey => $nVal)
					{
						$_POST['name'][$e_names[$nKey]['Code']] = $e_names[$nKey]['Value'];
					}
					
					// get description
					$descriptions = $rlDb -> fetch( array( 'Code', 'Value' ), array( 'Key' => 'account_fields+description+'.$e_key ), "AND `Status` <> 'trash'", null, 'lang_keys' );
					foreach ($descriptions as $pKey => $pVal)
					{
						$_POST['description'][$descriptions[$pKey]['Code']] = $descriptions[$pKey]['Value'];
					}
					
					// additional fields
					switch ($field_info['Type']){
						case 'text':
							$e_default = $rlDb -> fetch( array( 'Code', 'Value' ), array( 'Key' => 'account_fields+default+'.$e_key ), "AND `Status` <> 'trash'", null, 'lang_keys' );
	
							foreach ($e_default as $nKey => $nVal)
							{
								$_POST['text']['default'][$e_default[$nKey]['Code']] = $e_default[$nKey]['Value'];
							}
							
							$_POST['text']['condition'] = $field_info['Condition'];
							$_POST['text']['maxlength'] = $field_info['Values'];
						break;
						
						case 'textarea':
							$_POST['textarea']['maxlength'] = $field_info['Values'];
						break;
						
						case 'number':
							$_POST['number']['min_number'] = $field_info['Default'];
							$_POST['number']['max_number'] = $field_info['Values'];
						break;
						
						case 'date':
							$_POST['date']['mode'] = $field_info['Default'];
						break;
						
						case 'bool':
							$_POST['bool']['default'] = $field_info['Default'];
						break;
						
						case 'mixed':
							$_POST['mixed_data_format'] = $field_info['Condition'];
						case 'select':
							$_POST['data_format'] = $field_info['Condition'];
							
							$s_items = $rlDb -> fetch( array( 'Code', 'Key', 'Value' ), null, "WHERE `Key` LIKE 'account_fields+name+".$e_key."%' AND `Key` <> 'account_fields+name+".$e_key."' AND `Status` <> 'trash' ORDER BY `Key`", null, 'lang_keys' );
							foreach ($s_items as $nKey => $nVal)
							{
								$s_item = explode( '_', $s_items[$nKey]['Key'] );
								$s_item = array_reverse($s_item);

								$_POST[$field_info['Type']][$s_item[0]][$s_items[$nKey]['Code']] = $s_items[$nKey]['Value'];
							}
							
							// set default items
							if ( !empty($field_info['Default']) )
							{
								$_POST[$field_info['Type']]['default'] = $field_info['Default'];
							}
						case 'radio':
							$s_default = $rlDb -> fetch( array( 'Code', 'Key', 'Value' ), null, "WHERE `Key` LIKE 'account_fields+name+".$e_key."%' AND `Key` <> 'account_fields+name+".$e_key."' AND `Status` <> 'trash' ORDER BY `Key`", null, 'lang_keys' );

							foreach ($s_default as $nKey => $nVal)
							{
								$s_item = explode( '_', $s_default[$nKey]['Key'] );
								$s_item = array_reverse($s_item);
								$_POST[$field_info['Type']][$s_item[0]][$s_default[$nKey]['Code']] = $s_default[$nKey]['Value'];
							}

							// set default items
							if ( !empty($field_info['Default']) )
							{
								$_POST[$field_info['Type']]['default'] = $field_info['Default'];
							}
						break;
						
						case 'checkbox':
							$s_items = $rlDb -> fetch( array( 'Code', 'Key', 'Value' ), null, "WHERE `Key` LIKE 'account_fields+name+".$e_key."%' AND `Key` <> 'account_fields+name+".$e_key."' AND `Status` <> 'trash' ORDER BY `Key`", null, 'lang_keys' );
							foreach ($s_items as $nKey => $nVal)
							{
								$s_item = explode( '_', $s_items[$nKey]['Key'] );
								$s_item = array_reverse($s_item);

								$_POST[$field_info['Type']][$s_item[0]][$s_items[$nKey]['Code']] = $s_items[$nKey]['Value'];
							}
							
							// set default items
							if ( !empty($field_info['Default']) )
							{
								$ch_def = explode( ',', $field_info['Default'] );
								foreach ($ch_def as $cdItem)
								{
									$_POST[$field_info['Type']][$cdItem]['default'] = $cdItem;
								}
							}
						break;
						
						case 'image':
							$_POST['image']['resize_type'] = $field_info['Default'];
							
							if ($field_info['Default'] == 'C')
							{
								$resolution = explode( '|', $field_info['Values'] );
								$_POST['image']['width'] = $resolution[0];
								$_POST['image']['height'] = $resolution[1];
							}
							elseif ($field_info['Default'] == 'W')
							{
								$_POST['image']['width'] = $field_info['Values'];
							}
							elseif ($field_info['Default'] == 'H')
							{
								$_POST['image']['height'] = $field_info['Values'];
							}
						break;
						
						case 'file':
							$_POST['file']['type'] = $field_info['Default'];
						break;
						
						case 'accept':
							$accept_d = $rlDb -> fetch( array( 'Code', 'Value' ), array( 'Key' => 'account_fields+default+'.$e_key ), "AND `Status` <> 'trash'", null, 'lang_keys' );

							foreach ($accept_d as $nKey => $nVal)
							{
								$_POST['accept'][$accept_d[$nKey]['Code']] = $accept_d[$nKey]['Value'];
							}
						break;
					}
					
					$rlHook -> load('apPhpAccountFieldsPost');
				}
			}
		}
		
		/* get all languages */
		$allLangs = $rlLang -> getLanguagesList( 'all' );
		$rlSmarty -> assign_by_ref( 'allLangs', $allLangs );

		if ( isset($_POST['submit']) )
		{
			$errors = array();
			
			/* load the utf8 lib */
			loadUTF8functions('ascii', 'utf8_to_ascii', 'unicode');
			
			$f_type = $_POST['type'];
			
			/* check key */			
			$f_key = $rlValid -> xSql($_POST['key']);
			
			if ( !utf8_is_ascii( $f_key ) )
			{
				$f_key = utf8_to_ascii( $f_key );
			}
			
			if ( strlen( $f_key ) < 2 )
			{
				$errors[] = $lang['incorrect_phrase_key'];
			}
			
			/* check key exist (in add mode only) */
			if ($_GET['action'] == 'add')
			{
				$exist_key = $rlDb -> fetch( array('Key'), array('Key' => $f_key), null, null, 'account_fields', 'row' );

				if ( !empty($exist_key) )
				{
					$errors[] = str_replace( '{key}', "<b>\"".$f_key."\"</b>", $lang['notice_field_exist']);
				}
			}
			
			$f_key = $rlValid -> str2key( $f_key );
			
			/* check name */
			$f_name = $_POST['name'];
			
			foreach ($allLangs as $lkey => $lval )
			{
				if ( empty( $f_name[$allLangs[$lkey]['Code']] ) )
				{
					$errors[] = str_replace( '{field}', "<b>".$lang['name']."({$allLangs[$lkey]['name']})</b>", $lang['notice_field_empty']);
				}
				
				$f_names[$allLangs[$lkey]['Code']] = $f_name[$allLangs[$lkey]['Code']];
			}
			
			/* check field type */
			if ( empty($f_type) )
			{
				$errors[] = $lang['notice_type_empty'];
			}

			/*________________ check type's fields ________________*/
			
			/* check text type */
			$f_text_maxlength = $_POST['text']['maxlength'];
			
			if ( empty($f_text_maxlength) || ( $f_text_maxlength < 1 && $f_text_maxlength > 255 ) )
			{
				$f_text_maxlength = 50;
			}

			/* select/mixed type */
			if ($_POST['data_format'] || $_POST['mixed_data_format'])
			{
				$f_data['data_format'] = $_POST['data_format'];
				$f_data['mixed_data_format'] = $_POST['mixed_data_format'];
			}
			
			/* check date type */
			$f_date_mode = $_POST['date']['mode'];
			if ( $f_type == 'date' && empty($f_date_mode) )
			{
				$errors[] = $lang['notice_mode_not_chose'];
			}

			/* check file type */
			$f_file_type = $_POST['file']['type'];
			if ( $f_type == 'file' && empty($f_file_type) )
			{
				$errors[] = $lang['notice_type_empty'];
			}
			
			/* check agreement field */
			foreach ($allLangs as $lkey => $lval )
			{
				if ( $f_type == 'accept' && empty( $_POST['accept'][$allLangs[$lkey]['Code']] ) )
				{
					$errors[] = str_replace( '{field}', "<b>".$lang['agreement_text']."({$allLangs[$lkey]['name']})</b>", $lang['notice_field_empty']);
				}
			}

			/*______________ check type's fields end ______________*/
			
			$rlHook -> load('apPhpAccountFieldsValidate');
			
			if( !empty($errors) )
			{
				$rlSmarty -> assign_by_ref( 'errors', $errors );
			}
			else 
			{
				/* configuring data */
				$f_data['key'] = $f_key;
				$f_data['names'] = $f_names;
				$f_data['description'] = $_POST['description'];
				$f_data['required'] = (int)$_POST['required'];
				$f_data['map'] = (int)$_POST['map'];
				$f_data['status'] = $_POST['status'];
				$f_data['account_type'] = implode( ',', $_POST['account_type'] );
				
				switch ($f_type){
					case 'text':
						foreach ($allLangs as $lkey => $lval )
						{
							//if ( !empty($_POST['text']['default'][$allLangs[$lkey]['Code']]) )
							//{
								$f_data['default'][$allLangs[$lkey]['Code']] = $_POST['text']['default'][$allLangs[$lkey]['Code']];
							//}
						}
						$f_data['maxlength'] = (int)$f_text_maxlength;
						$f_data['condition'] = $_POST['text']['condition'];
					break;
					
					case 'textarea':
						$f_data['maxlength'] = (int)$_POST['textarea']['maxlength'];
					break;
					
					case 'number':
						$f_data['min'] = (int)$_POST['number']['min_number'];
						$f_data['max'] = (int)$_POST['number']['max_number'];
					break;
					
					case 'date':
						$f_data['mode'] = $f_date_mode;
					break;
					
					case 'bool':
						$f_data['default'] = (int)$_POST['bool']['default'];
					break;
					
					case 'select':
					case 'mixed':
					case 'radio':
						$f_data['default'] = (int)$_POST[$f_type]['default'];
						unset( $_POST[$f_type]['default'] );
						
						foreach ( $_POST[$f_type] as $selKey => $selVal)
						{
							foreach ($allLangs as $lkey => $lval )
							{
								$f_data['items'][$selKey][$allLangs[$lkey]['Code']] = $_POST[$f_type][$selKey][$allLangs[$lkey]['Code']];
							}
						}
					break;
					
					case 'checkbox':
						foreach ( $_POST[$f_type] as $selKey => $selVal)
						{
							foreach ($allLangs as $lkey => $lval )
							{
								$f_data['items'][$selKey][$allLangs[$lkey]['Code']] = $_POST[$f_type][$selKey][$allLangs[$lkey]['Code']];
							}
							$checkbox_default .= !empty($_POST[$f_type][$selKey]['default']) ? $_POST[$f_type][$selKey]['default'] . ',' : '';
						}

						$f_data['default'] = substr( $checkbox_default, 0, -1 );
					break;
					
					case 'image':
						$f_data['resize_type'] = $_POST['image']['resize_type'];
						$f_data['width'] = (int)$_POST['image']['width'];
						$f_data['height'] = (int)$_POST['image']['height'];
					break;
					
					case 'file':
						$f_data['file_type'] = $f_file_type;
					break;
					
					case 'accept':
						$f_data['accept'] = $_POST['accept'];
					break;
				};

				/* add/edit action */
				if ( $_GET['action'] == 'add' )
				{
					$rlHook -> load('apPhpAccountFieldsBeforeAdd');
					
					$action = $rlFields -> createRegisterField( $f_type, $f_data, $allLangs );
					$new_field_id = $rlFields -> addID;
					
					$rlHook -> load('apPhpAccountFieldsAfterAdd');
					
					$message = $lang['field_added'];
					$aUrl = array( "controller" => $controller, "action" => "add" );
				}
				elseif ( $_GET['action'] == 'edit' )
				{
					$rlHook -> load('apPhpAccountFieldsBeforeEdit');
					
					$action = $rlFields -> editRegisterField( $f_type, $f_data, $allLangs );
					$message = $lang['field_edited'];
					$aUrl = array( "controller" => $controller );
					
					$rlHook -> load('apPhpAccountFieldsAfterEdit');
				}
				
				if ( $action )
				{
					$reefless -> loadClass( 'Notice' );
					$rlNotice -> saveNotice( $message );
					$reefless -> redirect( $aUrl );
				}
			}
		}
	}	

	$rlHook -> load('apPhpAccountFieldsBottom');
	
	/* register ajax methods */
	$rlXajax -> registerFunction( array( 'deleteAField', $rlFields, 'ajaxDeleteAField' ) );
}